package way

import (
	"github.com/redis/go-redis/v9"
	"strconv"
	"sync"
)

//var redisMap = make(map[string]*redis.Client)

var redisMap sync.Map

func Redis(connection ...string) *redis.Client {
	connectionName := "default"
	if len(connection) > 0 {
		connectionName = connection[0]
	}
	if _, ok := redisMap.Load(connectionName); !ok {
		redisMap.Store(connectionName, newRedis(connectionName))
	}
	c, _ := redisMap.Load(connectionName)
	if client, ok := c.(*redis.Client); ok {
		return client
	} else {
		panic("redis 初始化错误")
	}
}

func newRedis(connectionName string) *redis.Client {
	configMap := Config().GetStringMapString("redis." + connectionName)
	if configMap == nil {
		panic("redis未配置")
	}
	db, err := strconv.Atoi(configMap["db"])
	if err != nil {
		panic("redis db 设置错误")
	}
	poolSize, err := strconv.Atoi(configMap["poolsize"])
	if err != nil {
		panic("redis poolsize 设置错误")
	}
	client := redis.NewClient(&redis.Options{
		Addr:     configMap["host"] + ":" + configMap["port"],
		Password: configMap["password"],
		DB:       db,
		PoolSize: poolSize,
	})
	return client
}
